import 'dart:convert';
import 'package:dio/dio.dart';

/// CURL 拦截器
class CURLInterceptors extends InterceptorsWrapper {

  @override
  onRequest(RequestOptions options, handler) async {
    try {
      List<String> components = ['curl -i'];
      components.add('-X ${options.method}');
      options.headers.forEach((k, v) {
        if (k != 'Cookie') {
          components.add('-H "$k: $v"');
        }
      });
      if (options.data != null) {
        if (options.data is FormData) {
          final fieldData = Map.fromEntries(options.data.fields);
          fieldData.forEach((key, value) {
            components.add('--form $key="$value"');
          });
          final fileData = Map.fromEntries(options.data.files);
          fileData.forEach((key, value) {
            // can show file name only
            components.add('--form =@"${(value as MultipartFile).filename}"');
          });
        } else if (options.headers['content-type'] == 'application/x-www-form-urlencoded') {
          options.data.forEach((k, v) {
            components.add('-d "$k=$v"');
          });
        } else {
          final data = json.encode(options.data).replaceAll('"', '\\"');
          components.add('-d "$data"');
        }
      }
      components.add('"${options.uri.toString()}"');
      _printBoxed(cURL: components.join('\t'));
    } catch (e) {
      print("CURLInterceptors ${e}");
    }
    return super.onRequest(options, handler);
  }

  void _printBoxed({required String cURL}) {
    print('');
    print('╔╣ cURL');
    print('║  $cURL');
    _printLine('╚');
  }

  void _printLine([String pre = '', String suf = '╝']) => print('$pre${'═' * 90}$suf');
}
